//
//  AuctionViewController.m
//  phmall
//
//  Created by admin on 2017/11/23.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "AuctionViewController.h"
#import "AuctionCell.h"
#import "GetDiscountCouponCell.h"
#import "CouponPageVC.h"
#import "AuctionDetailsVC.h"
#import "Orderheader.h"
#import "AuctionModel.h"
@interface AuctionViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>{
    Orderheader *_headView;
    NSInteger status,start;
}
@property(strong,nonatomic)UITableView *myTableview;
@property(nonatomic,strong)MBProgressHUD *hud;
@property(strong,nonatomic)NSMutableArray *auctionList;
@end

@implementation AuctionViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navBarBgAlpha=@"1.0";
    // 改变NavBar顶层View的颜色
    self.navigationController.navigationBar.barTintColor =  [UIColor whiteColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=Localized(@"拍卖疯抢");
 
    status=0;
    start=0;
    [self loadDataWithAuctionr:YES];
    self.emptyType=EmptyDataSetNone;
    [self setUI];
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    // Do any additional setup after loading the view.
    if (@available(iOS 11.0, *)) {
        self.myTableview.estimatedRowHeight = 0;
        self.myTableview.estimatedSectionFooterHeight = 0;
        self.myTableview.estimatedSectionHeaderHeight = 0;
        self.myTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    self.myTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footeRefresh)];
    self.myTableview.mj_footer.hidden=YES;
    self.myTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
}
-(void)HeaderRefresh{
    start=0;
    [self loadDataWithAuctionr:NO];
}
-(void)footeRefresh{
    start=self.auctionList.count;
    [self loadDataWithAuctionr:YES];
}
- (void)loadDataWithAuctionr:(BOOL)reload{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"auction"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:[NSString stringWithFormat:@"%ld",(long)start] forKey:@"start"];
    [parametersDic setValue:[NSString stringWithFormat:@"%ld",(long)status] forKey:@"status"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        if (start==0) {
            [self.auctionList removeAllObjects];
            self.myTableview.mj_footer.hidden=YES;
            if (reload) {
                [self.myTableview setContentOffset:CGPointMake(0, 0) animated:NO];
            }
        }
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSMutableArray *data=responseDict[@"data"];
                if (data.count==0) {
                    [self.myTableview.mj_header endRefreshing];
                    [self.myTableview.mj_footer endRefreshingWithNoMoreData];
                    if (reload) {
                        [self.myTableview reloadData];
                    }
                }else{
                    [self analysisDataWithOrderArray:data];
                }
            }
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        self.myTableview.mj_footer.hidden=YES;
        [self.auctionList removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
        [self.myTableview.mj_header endRefreshing];
        [self.myTableview.mj_footer endRefreshing];
        [self.hud hideAnimated:YES];
    }];
    
}
- (void)analysisDataWithOrderArray:(NSMutableArray *)array{
    //    [self.orderList removeAllObjects];
    for (NSDictionary *dict in array)
    {
        AuctionModel *model = [AuctionModel yy_modelWithDictionary:dict];
        model.goods_status=[NSString stringWithFormat:@"%ld",(long)status];
        [self.auctionList addObject:model];
    }
    if (self.auctionList.count!=0) {
        //数量少于2条时隐藏上拉加载
        if (self.auctionList.count<2) {
            self.myTableview.mj_footer.hidden=YES;
        }else{
            self.myTableview.mj_footer.hidden=NO;
        }
    }else{
        //数量为0条时隐藏上拉加载
        self.myTableview.mj_footer.hidden=YES;
    }
    [self.myTableview reloadData];
    [self.myTableview.mj_header endRefreshing];
    [self.myTableview.mj_footer endRefreshing];
}
-(void)setUI{
    
    __weak typeof(self) weakSelf = self;
    _headView = [[Orderheader alloc]init];
    _headView.backgroundColor=[UIColor colorWithHexString:@"#E7EBEE"];
    [self.view addSubview:_headView];
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.height.offset(40);
    }];
    _headView.backgroundColor=[UIColor colorWithHexString:@"#f8fafd"];
    _headView.itemClickAtIndex = ^(NSInteger index){
        weakSelf.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
        weakSelf.hud.detailsLabel.text =  Localized(@"加载中...");
        status=index;
        start=0;
        [weakSelf loadDataWithAuctionr:YES];
    };
    _headView.items = @[Localized(@"已开始"),Localized(@"未开始"),Localized(@"已结束")];
    
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(40);
        make.left.right.equalTo(self.view).priorityHigh();
        make.bottom.equalTo(self.view).with.offset(-self.tabBar_height).priorityHigh();
    }];
    
}

#pragma mark-通过点击button来改变scrollview的偏移量
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     return self.auctionList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AuctionCell *cell=[AuctionCell theShareCellWithTableView:tableView];
    AuctionModel *model =self.auctionList[indexPath.row];
    cell.model=model;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.hidesBottomBarWhenPushed=YES;
    AuctionDetailsVC *sear=[[AuctionDetailsVC alloc] init];
    [self.navigationController pushViewController:sear animated:YES];
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            return [UIImage imageNamed:@"订单缺失"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
    
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
    return YES;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:@"现在没有相关的活动！\n可以去看看有哪些想买的。"];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:20],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, 10)];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange(10, 12)];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}

#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    start=0;
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
    [self loadDataWithAuctionr:YES];
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.myTableview.contentOffset = CGPointZero;
}
//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
        _myTableview.emptyDataSetDelegate = self;
        _myTableview.emptyDataSetSource = self;
    }
    return _myTableview;
}
-(NSMutableArray *)auctionList{
    if (!_auctionList) {
        _auctionList=[[NSMutableArray alloc] init];
    }
    return _auctionList;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
